package org.aplombh.java.utils.multiThread.juc.pcp;

public class ProducerConsumer_Signal {

    public static void main(java.lang.String[] args) {
        TV tv = new TV();

        new Player(tv).start();
        new Audience(tv).start();
    }
}

class Player extends Thread {
    TV tv;

    public Player(TV tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            if (i % 2 == 0) {
                tv.play("Happy Camp");
            } else
                tv.play("Home With Kids");
        }
    }
}

class Audience extends Thread {
    TV tv;

    public Audience(TV tv) {
        this.tv = tv;
    }

    @Override
    public void run() {
        for (int i = 0; i < 10; i++) {
            tv.watch();
        }
    }
}

class TV {
    String program;
    boolean flag = true;

    public synchronized void play(String program) {
        if (!flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("TV performed " + program);
        this.notifyAll();
        this.program = program;
        this.flag = !this.flag;
    }

    public synchronized void watch() {
        if (flag) {
            try {
                this.wait();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }
        System.out.println("Audience watch the \"" + program + "\"");
        this.notifyAll();
        this.flag = !this.flag;
    }
}